package com.dingding.transfer.stamper.config;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.dingding.transfer.stamper.constant.Caches;
import com.dingding.transfer.stamper.entity.DeviceMapper;
import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
import com.github.benmanes.caffeine.cache.LoadingCache;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cache.CacheManager;
import org.springframework.cache.caffeine.CaffeineCache;
import org.springframework.cache.support.SimpleCacheManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author wangxiyuan
 * @description
 * @createDate 2021/3/30 15:57
 **/
@Configuration
@Slf4j
public class CaffeineConfig {
    @Bean
    public CacheManager cacheManager() {
        SimpleCacheManager cacheManager = new SimpleCacheManager();
        List<CaffeineCache> caches = new ArrayList<>();
        for (Caches c : Caches.values()) {
            Caffeine<Object, Object> caffeine = Caffeine.newBuilder().maximumSize(c.getMaxSize())// 最大缓存数据量
                    .initialCapacity(100);// 初始容量
            if(Caches.DEVICE_MAPPER.name().equals(c.name())){
                LoadingCache<Object, Object> cache = caffeine.build(o -> {
                    log.info("缓存自动加载中");
                    DeviceMapper deviceMapper = new DeviceMapper().selectOne(new QueryWrapper<DeviceMapper>().eq("device_name",o.toString())
                            .or().eq("uuid",o.toString()));
                    return deviceMapper.getUuid();
                });
                caches.add(new CaffeineCache(c.name(),cache));
            }else{
                Cache<Object, Object> cache = caffeine.expireAfterWrite(c.getTtl(), TimeUnit.SECONDS)// 过期清除
                        .build();
                caches.add(new CaffeineCache(c.name(),cache));
            }
        }
        cacheManager.setCaches(caches);
        return cacheManager;

    }
}
